package mmc.server.shell.ops.constant;

import mmc.server.shell.OperationNotAcceptedException;
import mmc.server.shell.ShellException;
import mmc.server.shell.ops.Constant;

public class StringValue extends Constant {

    public StringValue(String text) throws ShellException {
        super(text);
        
        if (text.trim().startsWith("\"") && text.trim().endsWith("\"")) {
        	String t = text.trim();
        	t = t.substring(t.indexOf('"')+1,t.lastIndexOf('"'));
        	//if(t.contains("\""))
        	//	throw new OperationNotAcceptedException(false, text + " is not a string-constant");
        	
        	StringBuilder sb = new StringBuilder();
        	for(int i=0;i<t.length();i++){
        		char c = t.charAt(i);
        		
        		if(c=='\\'){
        			if(t.length()<i+2)
        				throw new OperationNotAcceptedException(false, text + " ends with incomplete escape sequence!");
        			char c2 = t.charAt(i+1);
        			switch(c2){
        			case 'n':
        				sb.append('\n');
        				break;
        			case '\\':
        				sb.append('\\');
        				break;
        			case 't':
        				sb.append('\t');
        				break;
        			default:
        				sb.append(c2);
        				//throw new OperationNotAcceptedException(true, text + " uses unknown escape sequence: \\"+c2);
        			}
        			i++;
        		}else if(c=='"'){
        			throw new OperationNotAcceptedException(false, "string ended prematurely");
        		}else{
        			sb.append(c);
        		}
        	}
        	
        	super.text = sb.toString();
        } else {
            throw new OperationNotAcceptedException(false, text + " is not a string-constant");
        }
    }

    @Override
    public double execute() {
        throw new RuntimeException("not assignable to double!");
    }
    
    public static String getDescription(){
    	return formatHelpString("\"...\"","a String value");
    }
    
    public Object executeComplex(){
    	return text;
    }
    
    public Class<?> getOutputType(){
    	return String.class;
    }
    
    public static boolean hideInDescription(){
    	return true;
    }
}
